import javax.swing.*;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

class ClientSendThread extends Thread{
    ObjectOutputStream out;
    PongGamePanel game;
    GameState gs;
    ClientSendThread(ObjectOutputStream out, PongGamePanel game){
        this.out=out;
        this.game=game;
    }
    @Override
    public void run() {
        try {
            while (true){
                gs = game.getPlayerState();
                out.writeObject(gs);
                out.flush();
                Thread.sleep(10);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

class ClientThread extends Thread{
    ObjectInputStream in;
    PongGamePanel game;
    ClientThread(ObjectInputStream i, PongGamePanel game){
        in=i;
        this.game=game;
    }
    GameState gs;
    @Override
    public void run() {
        try {
            while (true){
                gs = (GameState) in.readObject();
                if(gs!=null){
                    synchronized (game){
                        game.setGameState(gs);
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}

public class TCPClient implements Runnable{
    //private static final String SERVER_IP = "localhost";
    private static final int PORT = 9527;
    private String server_ip;
    private PongGamePanel game;
    JFrame main;
    TCPClient(JFrame m, String ip){
        main = m;
        server_ip=ip;
    }

    public void start() {
        try {
            Socket clientSocket = new Socket(server_ip, PORT);
            startGame();
            ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream());
            ObjectOutputStream out = new ObjectOutputStream(clientSocket.getOutputStream());
            ClientThread clientThread = new ClientThread(in, game);
            clientThread.start();

            ClientSendThread clientSendThread = new ClientSendThread(out,game);
            clientSendThread.start();
            System.out.println("All Ready");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private void startGame(){
        game = new PongGamePanel(true,1);
        game.setBounds(0,0,800,600);
        main.getContentPane().removeAll();
        main.getContentPane().add(game);
        game.setVisible(true);
        main.repaint();
        game.requestFocus();

    }

    @Override
    public void run() {
        start();
    }
}
